/**
 * 读取文件内容
 */
import common from '../../tnxet-common.js';
import util from '../main-util.js';
import fs from 'fs';

export default {
    name: common.event.file.read,
    listen(filePath, withMeta, dataIfNonexistent) {
        return new Promise((resolve, reject) => {
            if (filePath) {
                filePath = util.file.getAbsolutePathBasedOnApp(filePath);
                if (fs.existsSync(filePath)) {
                    fs.readFile(filePath, common.event.file.encoding, (error, data) => {
                        if (error) {
                            reject(error);
                        } else {
                            let meta = undefined;
                            if (withMeta) {
                                const stat = fs.statSync(filePath);
                                meta = {
                                    modifiedTime: stat.mtime,
                                    size: stat.size,
                                };
                            }
                            resolve(data, meta);
                        }
                    });
                } else if (dataIfNonexistent !== undefined) {
                    resolve(dataIfNonexistent);
                } else {
                    reject([filePath + ' 不存在', false]);
                }
            } else {
                reject('Invalid filePath: ' + filePath);
            }
        });
    },
}
